<?php
/*
 * Copyright (c) 2011 Todd Brady
 *
 * PS3Theatre is freely distributable under the terms of the MIT license.
 * For details, see the MIT-Liscence web site: http://www.opensource.org/licenses/mit-license.php 
 */
 
 	include_once("../includes/db_connect.php");
	
	$typeString = "Movies";	
	$action=$_GET["action"];
	$movieId=$_GET["movieId"];
	$tmdbId=$_GET["tmdbId"];
	$movieTitle=$_GET["movieTitle"];
	$moveThe = $_SESSION['moveThe'];
	$filesTouched = array();
	$changesFound = false;
			
	if($action == 'scrapeAll'){
		scrapeAllMovies($typeString);
	}else if($action == 'scrapeMovieByDBId'){
		scrapeMovieByDBId($movieId);
	}else if($action == 'scrapeMovieByDBTitle'){
		scrapeMovieByDBTitle($movieId, $movieTitle, true);
	}else if($action == 'scrapeMovieByDBTitleJson'){
		scrapeMovieByDBTitle($movieId, $movieTitle, false);
	}else if($action == 'duplicateSelected'){
		duplicateSelected($movieId, $tmdbId, true);
	}else if($action == 'duplicateSelectedJson'){
		duplicateSelected($movieId, $tmdbId, false);
	}	
	
	//
	//
	//
	function scrapeMovieByDBId($movieId){
		//already in DB
		$movieTitle = getTitleByMovieId($movieId);
		
		$searchXml = searchByMovieName($movieTitle);
		$searchResults = $searchXml->xpath("/OpenSearchDescription/opensearch:totalResults");
					
		if($searchResults[0] == 0){
			//tell prev page there are no results
			echo 'no results';

		//if there is only 1 search result scrape and done			
		}else if($searchResults[0] == 1){
			$getIdXml = $searchXml->xpath("/OpenSearchDescription/movies/movie");
			$tmdbId = $getIdXml[0]->id[0];

			//parse out movie info from xml						
			$movieInfoXml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/131bce11e82d2af21ed5378e7e52cba5/".$tmdbId);
			$movieInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie");
			$castInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie/cast");
						
			//find director
			$dirIndex = getDirectorIndex($castInfo);

			//update record						
			updateRecord($movieId, $movieInfo, $castInfo, $dirIndex);

			//tell prev page to reload
			echo 'updated';

		}else{
			//create table html and pass it back to javascript method
			echo createDuplicateMovieTable($movieId, $movieTitle, $searchResults[0], $searchXml->xpath("/OpenSearchDescription/movies"));
			
		}
	}
	
	//
	//
	//
	function scrapeMovieByDBTitle($movieId, $movieTitle, $update){
		//already in db	
		$searchXml = searchByMovieName($movieTitle);
		$searchResults = $searchXml->xpath("/OpenSearchDescription/opensearch:totalResults");
					
		if($searchResults[0] == 0){
			//tell prev page there are no results
			echo 'no results';

		//if there is only 1 search result scrape and done			
		}else if($searchResults[0] == 1){
			$getIdXml = $searchXml->xpath("/OpenSearchDescription/movies/movie");
			$tmdbId = $getIdXml[0]->id[0];

			//parse out movie info from xml						
			$movieInfoXml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/131bce11e82d2af21ed5378e7e52cba5/".$tmdbId);
			$movieInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie");
			$castInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie/cast");
						
			//find director
			$dirIndex = getDirectorIndex($castInfo);
	
			if($update){
				//update record						
				updateRecord($movieId, $movieInfo, $castInfo, $dirIndex);
			}else{
				//return json so fields can be filled
				echo createMovieJsonRecord($movieId, $movieInfo, $castInfo, $dirIndex);
			}

		}else{
			//create table html and pass it back to javascript method
			echo createDuplicateMovieTable($movieId, $movieTitle, $searchResults[0], $searchXml->xpath("/OpenSearchDescription/movies"));
		}
	}
	
	//
	//
	//
	function duplicateSelected($movieId, $tmdbId, $update){
		//parse out movie info from xml						
		$movieInfoXml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/131bce11e82d2af21ed5378e7e52cba5/".$tmdbId);
		$movieInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie");
		$castInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie/cast");
						
		//find director
		$dirIndex = getDirectorIndex($castInfo);

		if($update){
			//update record						
			updateRecord($movieId, $movieInfo, $castInfo, $dirIndex);
			
			//tell prev page to reload
			echo 'success';
		}else{
			//return json so fields can be filled
			echo createMovieJsonRecord($movieId, $movieInfo, $castInfo, $dirIndex);
		}
	}
	
	//
	//
	//
	function duplicateSelectedJson($movieId, $tmdbId){
		//parse out movie info from xml						
		$movieInfoXml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/131bce11e82d2af21ed5378e7e52cba5/".$tmdbId);
		$movieInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie");
		$castInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie/cast");
						
		//find director
		$dirIndex = getDirectorIndex($castInfo);

		//update record						
		updateRecord($movieId, $movieInfo, $castInfo, $dirIndex);

		//tell prev page to reload
		echo 'success';
	}
	
	//
	//
	//
	function scrapeAllMovies($typeString){	
		set_time_limit(300);
		$directoriesListQuery = "SELECT d.id, d.computer_path, d.http_path from tbl_directories d, tbl_types t WHERE 		d.type_id=t.id and t.type='$typeString'";
			
		$directories=mysql_query($directoriesListQuery);
		$extArray = getExtensionArray($typeString);
		global $filesTouched;
		global $changesFound;
	
		while ($dirRow = mysql_fetch_array($directories)) {
			$path = $dirRow['computer_path'];
			$dirId = $dirRow['id'];
			$files = scandir($path);
	
			iterateThroughFiles($path, '', $files, $extArray, $dirId);
		}
		deleteFilesNotFound();
		
		if($changesFound){
			//tell requesting page it worked
			echo 'success';
		}else{
			//tell requesting page no changes
			echo 'no changes';
		}
	}
	
	//
	//
	//
	function getExtensionArray($typeString){
		$extensionsListQuery = sprintf("SELECT f.extension from tbl_fileextensions f, tbl_types t where f.type_id=t.id AND t.type='$typeString' and is_active='%s'",
							   	   mysql_real_escape_string("Y"));
					
		$extensions = mysql_query($extensionsListQuery);
		$extArray = array();

		//make file extension array
		while ($fileExtRow = mysql_fetch_array($extensions)) {
			$extArray[] = $fileExtRow['extension'];
		}
		
		return $extArray;
	}
	
	//
	//
	//
	function iterateThroughFiles($path, $subfolderPath, $files, $extArray, $dirId){
		for( $ctr = 0; $ctr < sizeof( $files ); $ctr++ ) {
			$fileName = $files[$ctr];
			$extStartPos = strrpos($fileName, '.');
			$ext = substr($fileName,$extStartPos+1);
			$justFileName = substr($fileName,0,$extStartPos);

			if($extStartPos == '' && $fileName != '.'){
				//its a directory...go inside directory and find files
				iterateThroughFiles($path,$subfolderPath.$fileName.'/',scandir($path.$subfolderPath.$fileName.'/'),$extArray,$dirId);
			}else{
				///make sure extension is valid
				if(in_array($ext,$extArray)){
					if(neverBeenScraped($fileName, $dirId, $subfolderPath)){
						//file has never been in database
						//looks good, go ahead and scrape
						$searchXml = searchByMovieName($justFileName);
						$searchResults = $searchXml->xpath("/OpenSearchDescription/opensearch:totalResults");
						
						//if there is only 1 search result scrape and done
						if($searchResults[0] == 1){
							$getIdXml = $searchXml->xpath("/OpenSearchDescription/movies/movie");
							$tmdbId = $getIdXml[0]->id[0];
	
							//parse out movie info from xml						
							$movieInfoXml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.getInfo/en/xml/131bce11e82d2af21ed5378e7e52cba5/".$tmdbId);
							$movieInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie");
							$castInfo = $movieInfoXml->xpath("/OpenSearchDescription/movies/movie/cast");
							
							//find director
							$dirIndex = getDirectorIndex($castInfo);
							
							insertRecord($dirId, $subfolderPath, $fileName, $movieInfo, $castInfo, $dirIndex);
						}else if($searchResults[0] == 0){
							//no results found...insert empty with error code 2
							insertEmptyRecord($dirId, $subfolderPath, $justFileName, $fileName, 2);
							
						}else if($searchResults[0] > 1){
							//more than 1 result found...insert empty record with error code 1
							insertEmptyRecord($dirId, $subfolderPath, $justFileName, $fileName, 1);
							
						}
					}
				}
			}
		}
	}
	
	//
	//
	//
	function neverBeenScraped($fileName, $dirId, $subfolderPath){
		$fileNameNeverQuery = sprintf("select id from tbl_movies where directory_id='%s' and subfolder_path='%s' and filename='%s'",
					  		  mysql_real_escape_string($dirId),
   						      mysql_real_escape_string($subfolderPath),
							  mysql_real_escape_string($fileName));
		$fileNameNeverCheck=mysql_query($fileNameNeverQuery);
		$numRows = mysql_num_rows($fileNameNeverCheck);
		global $filesTouched;
		
		if($numRows > 0){
			$row = mysql_fetch_array($fileNameNeverCheck);
			
			//add to files found array
			array_push($filesTouched, $row['id']);
		}
		
		return $numRows == 0;
	}
	
	//
	//
	//
	function deleteFilesNotFound(){
		global $filesTouched;
		$deleteString = "DELETE FROM tbl_movies WHERE id NOT IN ";
		$idString = "(";
		$i=0;
		
		while($i < count($filesTouched)){
			if($i != 0){
				$idString.=", ";
			}
				
			$idString.=$filesTouched[$i];
			$i++;
		}
		$idString.=");";
		
		$deleteQuery = mysql_query($deleteString.$idString) or die('error deleting movies: '.mysql_error());
	}
	
	//
	//
	//
	function searchByMovieName($fileName){
		$removeChars = array("'",".","/",",","[","]","{","}","(",")","|","-","_");
		$fileName = str_replace($removeChars, " ", $fileName);
		
		$searchXml = simplexml_load_file("http://api.themoviedb.org/2.1/Movie.search/en/xml/131bce11e82d2af21ed5378e7e52cba5/".$fileName);
		return $searchXml;
	}
	
	//
	//
	//
	function getDirectorIndex($castInfo){
		$dirIndex = 0;
	
		while($dirIndex < count($castInfo[0]) && ($castInfo[0]->person[$dirIndex][character] != '' || $castInfo[0]->person[$dirIndex][job] != 'Director')){
			$dirIndex++;
		}
		
		return $dirIndex;
	}
	
	function getTitleByMovieId($movieId){
		$titleGetQuery = sprintf("select title from tbl_movies where id=$movieId",
								  		  mysql_real_escape_string($movieId));
		$titleResult=mysql_query($titleGetQuery);
		$row = mysql_fetch_array($titleResult);
		
		return $row['title'];
	}
	
	//
	//
	//
	function createDuplicateMovieTable($movieId, $movieTitle, $numResults, $moviesXml){
		$tableString = "There are multiple search results for the title '<b>$movieTitle</b>'.".'  Please select the correct one:<br/><table width="95%" border="0" align="center" cellpadding="0" cellspacing="0" class="setupTable">
		<th></th><th>Title</th><th>Rel Date</th>';
		$i=0;
		
		while($i<$numResults){
			$class = "";
	
			if($i % 2 == 0){
				$class = 'class="alt"';
			}
			
			$tableString.="<tr><td $class><div align='center'>";
			$tableString.='<a href="#" onclick="javascript:selectDup('.$movieId.", ".$moviesXml[0]->movie[$i]->id.')">Select</a></div></td>'."<td $class>";
			$tableString.=$moviesXml[0]->movie[$i]->name."</td><td $class>";
			$tableString.=$moviesXml[0]->movie[$i]->released.'</td></tr>';	
			
			$i++;
		}
		$tableString.='<tr>
    <td class="footer" colspan="3"></td>
  </tr></table>';
		return $tableString;
	}
	
	//
	//
	//
	function createMovieJsonRecord($movieId, $movieInfo, $castInfo, $dirIndex){
		$json = "{";
		$json.='"title" : "'.str_replace('"','\"',iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->name)).'", ';
		$json.='"tmdbId" : "'.str_replace('"','\"',$movieInfo[0]->id).'", ';
		$json.='"overview" : "'.str_replace('"','\"',iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->overview)).'", ';
		$json.='"rating" : "'.str_replace('"','\"',$movieInfo[0]->rating).'", ';
		$json.='"certification" : "'.str_replace('"','\"',iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->certification)).'", ';
		$json.='"releasedDate" : "'.str_replace('"','\"',iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->released)).'", ';
		$json.='"runtime" : "'.str_replace('"','\"',$movieInfo[0]->runtime).'", ';
		$json.='"budget" : "'.str_replace('"','\"',$movieInfo[0]->budget).'", ';
		$json.='"revenue" : "'.str_replace('"','\"',$movieInfo[0]->revenue).'", ';
		$json.='"director" : "'.str_replace('"','\"',iconv("UTF-8", "ISO-8859-1//TRANSLIT",$castInfo[0]->person[$dirIndex][name])).'"';
		$json.="}";
		
		return $json;		
	}
	
	//
	//
	//
	function insertRecord($dirId, $subfolderPath, $fileName, $movieInfo, $castInfo, $dirIndex){
		global $filesTouched;
		global $changesFound;
		
		$changesFound = true;
		
		$insertQuery = sprintf("INSERT INTO tbl_movies (directory_id,subfolder_path,filename,title,tmdb_id,overview,rating,certification,released_date,runtime,budget,revenue,director,is_watched)
VALUES (%s,'%s','%s','%s',%s,'%s','%s','%s','%s',%s,%s,%s,'%s','%s')", 
							   	   mysql_real_escape_string($dirId),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($fileName),
								   mysql_real_escape_string(updateTitle(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->name))),
								   mysql_real_escape_string($movieInfo[0]->id),
								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->overview)),
								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->rating)),
								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->certification)),
								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->released)),
								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->runtime)),
   								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->budget)),
   								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->revenue)),
   								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$castInfo[0]->person[$dirIndex][name])),
								   'N');

					//insert movie record
					mysql_query($insertQuery) or die('error inserting record: query: '.$insertQuery.'error:'.mysql_error());
					
					//add to files found array
					array_push($filesTouched, mysql_insert_id());
	}
	
	//
	//
	//
	function insertEmptyRecord($dirId, $subfolderPath, $title, $fileName, $errorId){
		global $filesTouched;
		global $changesFound;
		
		$changesFound = true;
		
		$insertQuery = sprintf("INSERT INTO tbl_movies (directory_id,subfolder_path,filename,title,tmdb_id,error_id,is_watched)
VALUES (%s,'%s','%s','%s',%s,%s,'%s')", 
							   	   mysql_real_escape_string($dirId),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($fileName),
								   mysql_real_escape_string(updateTitle($title)),
								   mysql_real_escape_string(-1),
								   $errorId,
								   'N');

		//insert movie record
		mysql_query($insertQuery) or die('error inserting record: query: '.$insertQuery.'error:'.mysql_error());
					
		//add to files found array
		array_push($filesTouched, mysql_insert_id());
	}
	
	//
	//
	//
	function updateRecord($movieId, $movieInfo, $castInfo, $dirIndex){
		$updateQuery = sprintf("UPDATE tbl_movies SET title='%s',tmdb_id=%s,error_id=null,overview='%s',rating=%s,certification='%s',released_date='%s',runtime=%s,budget=%s,revenue=%s,director='%s' WHERE id=%s", 
								   mysql_real_escape_string(updateTitle(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->name))),
								   mysql_real_escape_string($movieInfo[0]->id),
								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->overview)),
								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->rating)),
								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->certification)),
								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$movieInfo[0]->released)),
								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->runtime)),
   								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->budget)),
   								   mysql_real_escape_string(cleanXmlNumber($movieInfo[0]->revenue)),
   								   mysql_real_escape_string(iconv("UTF-8", "ISO-8859-1//TRANSLIT",$castInfo[0]->person[$dirIndex][name])),
								   mysql_real_escape_string($movieId));

					//update movie record
					mysql_query($updateQuery) or die('error updating record: query: '.$updateQuery.'error:'.mysql_error());
	}
	
	//
	//
	//
	function updateTitle($movieTitle){
		global $moveThe;
		
		if($moveThe == 'Y' && substr($movieTitle,0,4) == 'The '){
			return substr($movieTitle,4).', The';
		}else{
			return $movieTitle;
		}
	}
	
	//
	//
	//
	function cleanXmlNumber($number){
		if($number == ''){
			return 0;
		}else{
			return $number;
		}
	}
?> 